<!--
  功能：初始化功能描述
  作者：zichen-jiang
  邮箱：18307106535@163.com
  版本：v1.0.2
  修改内容：vue2.0初始化模板
  修改人员：zicheng-jiang
  修订时间：2020.10.01
  组件生成时间：2022年06月24日 10:25:31
-->
<template>
  <div class="dynamic">
    <div class="bg"></div>
    <section class="animate__animated animate__lightSpeedInLeft">
      <div class="section-left">
        <div class="section-left-boxfabu">
          <a-textarea
            v-model="valueText"
            placeholder="分享心得，分享喜乐！"
            :auto-size="{ minRows: 5, maxRows: 7 }"
          />
          <div class="submit-imglist">
            <div class="submit-imglist-box" v-for="(item, index) in imglist" :key="index">
              <img
                v-lazy="baseUrl + item"
                class="image"
                preview="1"
                :preview-text="index"
              />
              <a-icon
                type="close-circle"
                class="delete_img"
                @click="delete_img(item, index)"
              />
            </div>
          </div>
          <div class="section-left-submit">
            <div style="width: 30px" v-if="imglist.length == 9"></div>
            <a-upload
              name="avatar"
              :show-upload-list="false"
              :accept="fileAccept"
              :customRequest="uploadImg"
              :beforeUpload="beforeUpload"
              v-if="imglist.length != 9"
            >
              <img src="../../assets/photo.png" alt />
              <span style="margin-left: 10px">{{ imglist.length }}/9</span>
            </a-upload>
            <div>
              <span style="font-size: 12px; margin-right: 10px"
                >{{ valueText.trim().length }}/300</span
              >
              <a-button
                type="primary"
                @click="submit"
                :disabled="valueText.trim() == '' || valueText.trim().length > 300"
                >发布</a-button
              >
            </div>
          </div>
        </div>
        <div class="section-left-content">
          <div
            class="section-left-content-box"
            v-for="(item, index) in contentlist"
            :key="index"
          >
            <div class="content-user">
              <img :src="baseUrl + item.createUserimg" alt />
              <div>
                <p class="content-user-name">
                  {{ item.createUser }}
                  <img
                    src="../../assets/rz.png"
                    alt
                    style="width: 18px !important; margin-top: -3px"
                    v-if="item.createUserrole === '0'"
                  />
                </p>
                <p class="content-user-date">
                  <span style="color: #1890ff">{{
                    item.createUserrole === "0"
                      ? "超级管理员"
                      : item.createUserrole === "1"
                      ? "管理员"
                      : ""
                  }}</span>
                  {{ getTime(item.createDate) }}
                </p>
              </div>
            </div>
            <div class="content-box">
              <div>{{ item.dynamicText }}</div>
              <div class="content-image">
                <div v-for="(ele, i) in item.dynamicImage" :key="i">
                  <img :src="baseUrl + ele" preview="1" :preview-text="index" />
                </div>
              </div>
            </div>
            <div class="content-give">
              <div>
                <img
                  src="../../assets/dianzan1.png"
                  alt
                  title="点个赞吧"
                  style="height: 19px"
                  @click="give(item)"
                  v-if="!givelist(item)"
                />
                <img
                  src="../../assets/dianzan.png"
                  alt
                  title="已点赞了哦"
                  style="width: 19px; height: 17px"
                  v-if="givelist(item)"
                />
                <span class="content-givenum">{{ item.dynamicGive.length }}人已赞</span>
              </div>
              <div @click="getDetails(item)">
                <img
                  src="../../assets/pl.png"
                  alt
                  title="评论一下吧"
                  style="height: 22px"
                />
                <span class="content-givenum"
                  >{{ item.dynamiccomment.length }}条评论</span
                >
              </div>
            </div>
          </div>
        </div>

        <div class="fenye">
          <a-pagination
            show-quick-jumper
            :default-current="1"
            :total="total"
            @change="onChange"
            v-if="total > 10"
          />
        </div>
      </div>
      <div class="section-right">
        <RightBox />
      </div>
    </section>
  </div>
</template>
<script>
//import(导入)其他文件（如：组件，工具js，第三方插件js，json文件，图片文件等）
import { requset } from "@/api";
import { uploads } from "@/utils/upload";
import { timeago } from "@/utils/timeago";
import RightBox from "./modules/rightBox";

export default {
  name: "dynamic",
  /**注册组件*/
  components: { RightBox },
  /**接受父组件传值*/
  props: {},
  data() {
    return {
      fileAccept: "image/gif, image/jpeg, image/jpg, image/png, image/svg",
      valueText: "",
      userInfo: JSON.parse(localStorage.getItem("userInfo")),
      baseUrl: process.env.VUE_APP_API_BASE_URL,
      imglist: [],
      contentlist: [],
      pageSize: 10,
      pageIndex: 1,
      total: 0,
    };
  },
  /**计算属性*/
  computed: {},
  /**监听data数据变化*/
  watch: {},
  /**创建组件时执行(有VM对象this)*/
  created() {},
  /**加载完组件时执行(主要预处理数据)*/
  mounted() {
    this.getlist();
  },
  /**所有方法*/
  methods: {
    // 分页
    onChange(pageNumber) {
      this.pageIndex = pageNumber;
      this.getlist();
    },
    //跳转详情
    getDetails(item) {
      let routeUrl = this.$router.resolve({
        path: "/dynamic/dynamicDetails/",
        query: { username: item.createUser, id: item.id },
      });
      window.open(routeUrl.href, "_blank");
    },
    //点赞
    give(item) {
      if (!localStorage.getItem("token")) {
        this.$message.error("请先进行登录在进行点赞！");
        setTimeout(() => {
          this.$router.push("/login");
        }, 500);
        return;
      }
      let params = {
        id: item.id,
        userId: this.userInfo.userId,
        userName: this.userInfo.userName,
        tongzhiuserid: item.createUserId,
      };
      requset("post", "/dynamic/give", params).then((res) => {
        if (res.data.code == 200) {
          this.$message.success(res.data.msg);
          this.getlist();
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    givelist(item) {
      let giveshow = false;
      if (this.userInfo) {
        item.dynamicGive.forEach((ele) => {
          if (this.userInfo.userId == ele.userId) {
            giveshow = true;
          }
        });
      }
      return giveshow;
    },
    // 时间 几天前 几月前
    getTime(time) {
      return timeago(time);
    },
    // 获取动态数据
    getlist() {
      let params = {
        pageSize: this.pageSize,
        pageIndex: this.pageIndex,
      };
      requset("post", "/dynamic/list", params).then((res) => {
        if (res.data.code == 200) {
          this.contentlist = res.data.data;
          this.total = res.data.total;
          this.$previewRefresh();
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    //发布
    submit() {
      if (!localStorage.getItem("token")) {
        this.$message.error("请先进行登录在发布动态！");
        setTimeout(() => {
          this.$router.push("/login");
        }, 500);
        return;
      }
      let params = {
        createUserId: this.userInfo.userId,
        dynamicText: this.valueText,
        dynamicImage: this.imglist,
      };
      requset("post", "/dynamic/create", params).then((res) => {
        if (res.data.code == 200) {
          this.imglist = [];
          this.valueText = "";
          this.$message.success(res.data.msg);
          this.getlist();
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    //上传文件前校验
    beforeUpload(file) {
      const extension1 = file.name.split(".")[1] === "jpg";
      const extension2 = file.name.split(".")[1] === "jpeg";
      const extension3 = file.name.split(".")[1] === "png";
      const extension4 = file.name.split(".")[1] === "gif";
      const extension5 = file.name.split(".")[1] === "svg";
      if (!extension1 && !extension2 && !extension3 && !extension4 && !extension5) {
        this.$message.error("别乱选，好好上传图片，再乱选头给你打歪！");
      }
      return extension1 || extension2 || extension3 || extension4 || extension5;
    },
    // 文件上传
    uploadImg(upload) {
      if (!localStorage.getItem("token")) {
        this.$message.error("请先进行登录在进行点赞！");
        setTimeout(() => {
          this.$router.push("/login");
        }, 500);
        return;
      }
      if (this.imglist.length == 9) {
        this.$message.error("请只能上传九张图片！");
        return;
      }
      uploads("/dynamic/uploads", upload.file).then((res) => {
        if (res.data.code == 200) {
          this.imglist.push(res.data.imgUrl);
          this.$previewRefresh();
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    //删除图片
    delete_img(item, index) {
      requset("post", "/dynamic/deleteImg", { url: item }).then((res) => {
        if (res.data.code == 200) {
          this.imglist.splice(index, 1);
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
  },
};
</script>
<style scoped>
/* @import url(); 引入css类 */
@import url(./modules/style.css);
::v-deep textarea.ant-input {
  border: none;
}
.fenye {
  margin: 30px 0;
}

/* 如果浏览器窗口小于 900px */
@media only screen and (max-width: 900px) {
  section {
    width: 100%;
  }
  .section-left {
    width: 100%;
  }
  .section-right {
    display: none !important;
  }
}
</style>
